import time
import re
import json
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class GuangdongGzsbyqrmzfA02DPolicy(BaseTaxPolicySpider):
    name = "guangdong_gzsbyqrmzf_a02d_policy"

    province: str = "广东省"  # 取表格
    city: str = "广州市"  # 取表格
    county: str = "白云区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "广州市白云区人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.by.gov.cn/gkmlpt/policy"  # 注明入口网址，以便后续排错
    host_url = url.split('.gov.cn')[0] + '.gov.cn'

    def start_requests(self):
        url = [
            "https://www.by.gov.cn/gkmlpt/policy"
        ]
        callback = self.detail_requests
        yield scrapy.Request(self.url, callback=callback)

    def detail_requests(self, response, **kwargs):
        for name in ["政策"]:
            tree_list = response.xpath(".").re(r"""TREE:\s*(\[.*?\]),""")[0]
            APP_URL = response.xpath(".").re(r"""APP_URL:\s*\'(.*?)\',""")[0]
            sid = response.xpath(".").re(r"""SID:\s*'?"?(\d+)""")[0]
            for tree in json.loads(tree_list):
                if tree['name'] == name:
                    print(tree)
                    url = f"{APP_URL}/gkmlpt/api/all/{tree['id']}?page=1&sid={sid}"
                    yield response.follow(url, callback=self.parse_list, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['articles']:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.get('created_at')
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = math.ceil(response.json()['total'] / 100)
            total = response.json()['total']
            print(f"{response.url} page: {pages} total: {total}")
            for page_num in range(2, int(pages) + 1):
                url = re.sub(r"page=1", r"page={}".format(page_num), response.url)
                print(url)
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl guangdong_gzsbyqrmzf_a02d_policy".split())
